package dbbaas;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.ws.rs.HttpMethod;

public class EncodingFilter implements Filter {
	private static String DEFAULTENCODING = "iso-8859-1";
	private static String ENCODING = "UTF-8";

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setCharacterEncoding(ENCODING);
		response.setContentType("text/html");
		HttpServletRequest req = (HttpServletRequest) request;
		if (HttpMethod.GET.equals(req.getMethod())) {
			// get处理
			request = new EncodingRequest(req);

		} else if (HttpMethod.POST.equals(req.getMethod())) {
			// post处理
			request.setCharacterEncoding(ENCODING);
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String defaultEncoding = config.getInitParameter(DEFAULTENCODING);
		if (!(defaultEncoding == null || defaultEncoding.length() == 0)) {
			DEFAULTENCODING = defaultEncoding;
		}
		String encoding = config.getInitParameter(ENCODING);
		if (!(encoding == null || encoding.length() == 0)) {
			ENCODING = encoding;
		}
	}

	private class EncodingRequest extends HttpServletRequestWrapper {
		private HttpServletRequest request;

		public EncodingRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}

		@Override
		public String getParameter(String name) {
			String value = request.getParameter(name);
			if (value == null || value.length() == 0) {
				return value;
			}
			try {
				value = new String(value.getBytes(DEFAULTENCODING), ENCODING);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return value;
		}
	}

}
